<template>
  <div>
    <LayoutPanel
      :title="$t('license.tablicense')"
      class="private-common-wrapper"
    >
      <div class="flex-between" style="margin-bottom: 16px">
        <rj-space>
          <a-button type="primary" @click="addLicense()">
            {{ $t('license.addTitle') }}
          </a-button>
        </rj-space>
        <rj-space v-if="isExitLicense">
          <span>{{ $t('license2.currentNum', [this.supportNum]) }}</span>
        </rj-space>
      </div>
      <rj-table
        class="upgrade-device-list"
        :columns="columns"
        :data-source="licenses"
        :rowKey="(row) => row.sn"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template slot="time" slot-scope="text">
          {{ moment(text).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template slot="validity"> {{ $t('license2.foreve') }} </template>
        <template slot="opert" slot-scope="text, record">
          <a-popconfirm
            :title="$t('license.deleteTip')"
            @confirm="delLicense(record)"
          >
            <a-icon type="delete" class="question-icon"
          /></a-popconfirm>
        </template>
      </rj-table>

      <rj-modal
        :title="$t('license.addTitle')"
        :visible="visible"
        :maskClosable="false"
        :width="600"
        :footer="null"
        @cancel="handelModalCancel"
      >
        <div class="export-license">
          <div class="step-cls" style="margin-top: -8px">
            {{ $t('license2.step1') }}
          </div>
          <a-form-model
            :model="formModel"
            :wrapper-col="wrapperCol"
            :rules="rules"
            ref="ruleForm"
          >
            <a-form-model-item prop="licenseKey" label="">
              <a-input
                v-model="formModel.licenseKey"
                :placeholder="$t('license.keyvalidate')"
              />
            </a-form-model-item>
          </a-form-model>
          <a-button type="primary" @click="getLicense">{{
            $t('license2.getDat')
          }}</a-button>
        </div>

        <div>
          <div class="step-cls">{{ $t('license2.step2') }}</div>
          {{ $t('license2.step2Tip1') }}
          <a @click="onGotoRjAuth">{{ $t('license2.rjAuthSys') }}</a>
          {{ $t('license2.step2Tip2') }}
        </div>
        <div class="box">
          <div class="step-cls">{{ $t('license2.step3') }}</div>
          <a-upload
            :multiple="false"
            list-type="picture-card"
            :show-upload-list="false"
            :fileList="fileList"
            class="avatar-uploader"
            :before-upload="beforeUpload"
            :accept="accept.toString()"
          >
            <a-button type="primary">{{ $t('license.import') }}</a-button>
          </a-upload>
        </div>
      </rj-modal>
    </LayoutPanel>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import {
  requestHttp,
  maccApi,
  requestHttpDownload,
  requestHttpUploadByForm,
} from '@utils/index';
import { RjTable, RjModal } from '@components';
import i18n from '@/locales';
import moment from 'moment-timezone';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';

const COLUMNS = [
  {
    title: i18n.t('license.tablicense'),
    dataIndex: 'sn',
    key: 'sn',
  },
  {
    title: i18n.t('license.tabnum'),
    dataIndex: 'productCode',
    key: 'productCode',
  },
  {
    title: i18n.t('license.tabpoduct'),
    dataIndex: 'productDesc',
  },
  {
    title: i18n.t('license.tabtime'),
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'time' },
  },
  {
    title: i18n.t('license.validity'),
    scopedSlots: { customRender: 'validity' },
  },
  {
    title: i18n.t('common.action'),
    dataIndex: 'opert',
    scopedSlots: { customRender: 'opert' },
  },
];

export default {
  name: 'licenseManage',
  props: {},
  components: {
    'rj-table': RjTable,
    'rj-modal': RjModal,
    LayoutPanel,
  },
  data() {
    let validateName = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('license.keySpace')));
      }
      let reg = false;
      let deviceNameRegex = /^[\w\-.]+$/;
      if (deviceNameRegex.test(value)) {
        let strByteLen = value.length;
        if (strByteLen >= 28 && strByteLen <= 64) {
          reg = true;
        }
      }
      if (!reg) {
        return callback(new Error(this.$t('license.keyvalidate')));
      }
      callback();
    };
    return {
      moment,
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
      columns: COLUMNS,
      selectedRowKeys: [],
      selectedRows: [],
      licenses: [],
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10,
      },
      searchParam: {
        auth_type: '',
        online_status: '',
        account: '',
      },
      visible: false,
      formModel: {
        licenseKey: '',
      },
      rules: {
        licenseKey: [
          {
            required: true,
            validator: validateName,
            trigger: 'blur',
          },
        ],
      },
      accept: ['.lic'], //上传类型
      fileList: [],
      isExitLicense: false,
      licenseStatus: {
        tenantId: 40,
        usedPackage: 0, // 已使用服务包数
        unusedPackage: 204000, // 未使用服务包数,
        totalPackage: 204000, // 服务包总数
        currentMonthUsingPackage: 0,
        currentStatus: 'out-service',
        activeTime: 1561910400000,
        currentMonth: 1559318400000,
        estimateTerminationTime: 2098454400000, // 预估到期时间
      },
      supportNum: 0,
    };
  },

  mounted() {
    this.timezone = this.$store.state.User.userInfo.timeZone;
    this.initView();
  },
  created() {},
  methods: {
    onGotoRjAuth() {
      window.open(`https://pa.ruijie.com.cn/main_software.jsf`, '_blank');
    },
    initView() {
      this.getList();
    },
    handleTableChange(pagination) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      this.pagination = pager;
      this.getList();
    },
    /**
     *
     * 获取列表
     * */
    async getList() {
      const ret = await requestHttp({
        api: `${maccApi.LICENSE_GET_API}?page=${this.pagination.current}&per_page=${this.pagination.pageSize}`,
        method: 'GET',
      });
      if (ret.code == 0) {
        this.licenses = ret.dataList;
        this.pagination.total = ret.totalCount;
        this.supportNum = ret.supportNumber;

        if (ret.totalCount > 0) {
          this.isExitLicense = true;
        }
      } else {
        this.licenses = [];
        this.pagination.total = 0;
      }
    },
    getTime() {
      if (this.licenseStatus.estimateTerminationTime) {
        let time =
          this.licenseStatus.estimateTerminationTime - new Date().getTime();
        if (time > 0) {
          //在线时长,默认单位s
          let activeTime = parseInt(time / 1000);
          let hour = Math.floor(activeTime / 3600);
          activeTime = activeTime % 3600;
          let minute = Math.floor(activeTime / 60);
          activeTime = activeTime % 60;
          let second = activeTime;
          return hour + 'h ' + minute + 'm ' + second + 's';
        }
      }
      return '--';
    },
    async delLicense(record) {
      const ret = await requestHttp({
        api: `${maccApi.LICENSE_DELETE_API.replace('{code}', record.sn)}`,
        method: 'DELETE',
      });
      if (ret.code == 0) {
        this.$message.success(this.$t('common.delSuccess'));
        this.getList();
      } else {
        this.$message.success(ret.msg);
      }
    },
    /**
     * 获取下载接口的data
     */
    getDownloadData() {
      let api = `${maccApi.LICENSE_CREATE_API.replace(
        '{sn}',
        this.formModel.licenseKey
      )}`;
      let data = {
        api: api,
        fileName: this.formModel.licenseKey + '.dat',
        attachment: true, //是否以附件形式下载，默认true
        method: 'GET',
        module: 'default', //api模块，用于区分service 部署的ip,不传默认default，非/service/api/的模块都需要传该参数，巡检--inspection，日志--logbiz，终端管理--pyservice

        contentType: 'application/dat;charset=UTF-8',
      };
      return data;
    },
    //直接下载License
    downloadLicense() {
      let data = this.getDownloadData();
      requestHttpDownload(JSON.stringify(data)).then((ret) => {
        //真正下载
        let url = '/webproxy/common/file/download';
        let downloadData = ret.data.downloadData;
        url += '?downloadData=' + downloadData;
        window.open(url);
      });
    },
    async addLicense() {
      this.visible = true;
    },
    async getLicense() {
      await this.getList();
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.downloadLicense();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    beforeUpload(file) {
      const fileNames = file.name.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      if (this.accept.indexOf(fileType) > -1) {
        this.fileName = file.name;
        this.fileUrl = window.URL.createObjectURL(file);
        this.fileList = [file];
        //自定义上传
      } else {
        this.$message.warning(this.$t('components.excelImport.upfailfailure'));
      }
      return false;
    },
    async importLicense() {
      let fileName = encodeURIComponent(this.fileName);
      let api = `${maccApi.LICENSE_IMPORT_API}`;
      this.uploadData = {
        uploadData: JSON.stringify({
          api: api,
          method: 'POST',
          module: 'default',
          fileName: 'file', // tommy 240701 ? 这个是固定的
          contentType: 'multipart/form-data', //此接口必须设置contentType
        }),
      };
      this.loading = true;
      let params = {
        file: this.fileList[0],
        uploadData: this.uploadData.uploadData,
      };

      let res = await requestHttpUploadByForm(params);
      if (res && res.code == 0) {
        this.fileList = [];
        this.visible = false;
        this.$message.success(this.$t('components.excelImport.importsuccess'));
        this.getList();
      } else {
        this.$message.warning(res.msg);
      }
    },
    handelModalCancel() {
      this.visible = false;
    },
  },
  watch: {
    fileList() {
      if (this.fileList.length > 0) {
        this.importLicense();
      }
    },
  },
  computed: {
    ...mapState('Group', ['groupId']),
  },
};
</script>
<style lang="less" scoped>
.private-common-wrapper {
  padding: 16px;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.page {
  padding: 16px;
}
.flex-between {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
.normal-tip {
  color: @success-color;
}
.error-tip {
  color: @error-color;
}
.fontweight {
  font-weight: bold;
}
.export-license {
  /deep/.ant-form-item {
    margin-bottom: 8px;
  }
}
.step-cls {
  margin-top: 24px;
  margin-bottom: 8px;
  font-weight: 500;
}
.box {
  /deep/ .ant-upload-picture-card-wrapper {
    width: 160px;
  }
  /deep/ .ant-upload.ant-upload-select-picture-card {
    width: 104px;
    height: 32px;
  }
  /deep/ .ant-upload {
    padding: 0px;
    background-color: #fff;
    border: 0px;
    margin-left: -16px;
    margin-top: 8px;
  }
}
.question-icon {
  cursor: pointer;
}
</style>
